package com.jeeplus.modules.web.wx;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.Collections3;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.monitor.model.configuration.ReceiveXmlEntity;
import com.jeeplus.modules.monitor.utils.Achieve;
import com.jeeplus.modules.monitor.utils.MoneyUtils;
import com.jeeplus.modules.monitor.utils.utils.MD5Util;
import com.jeeplus.modules.monitor.utils.utils.MyX509TrustManager;
import com.jeeplus.modules.monitor.utils.utils.Sha1Util;
import com.jeeplus.modules.web.entity.WxOrder;
import com.jeeplus.modules.web.entity.WxOrders;
import com.jeeplus.modules.web.entity.WxUser;
import com.jeeplus.modules.web.entity.YjEquipment;
import com.jeeplus.modules.web.entity.wx.YsUser;
import com.jeeplus.modules.web.mapper.*;
import com.jeeplus.modules.web.service.*;
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.ConnectException;
import java.net.URL;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by rongj on 2017/8/6.
 */
@Controller
@RequestMapping(value = "/wx/order")
public class YjOrderController extends BaseController {
	@Autowired
	WxUserMapper wxUserMapper;
	@Autowired
	WxUserWalletService wxUserWalletService;

	@Autowired
	WxOrderMapper wxOrderMapper;
	@Autowired
	WxOrderService wxOrderService;

	@Autowired
	YjEquipmentMapper yjEquipmentMapper;

	@Autowired
	WxUserIntegrationRecordMapper wxUserIntegrationRecordMapper;
	@Autowired
	private WxGoodsRecordService wxGoodsRecordService;
	@Autowired
	private WxAgentsRecordingService wxAgentsRecordingService; // 获取Service 接口 防止注入失败

	private static final Logger log = LoggerFactory.getLogger(YjOrderController.class);

	/**
	 * @return
	 */
	@RequestMapping("/pay")
	@ResponseBody
	public Map<String, Object> get_openId(HttpServletRequest request) throws ParseException {
		String token = request.getParameter("token");
		String name = request.getParameter("name");
		String type = request.getParameter("type");
		String text = request.getParameter("text");
		String money = request.getParameter("money");
		String addOrderMoney = request.getParameter("addOrderMoney") == null ? "0"
				: request.getParameter("addOrderMoney");
        Map<String, String[]> parameterMap = request.getParameterMap();
        logger.info("充值订单信息,openid:"+ (StringUtils.isNotBlank(token)?token:"异常OPENID:"+token)+",充值金额:"+money);
        Map<String, Object> map = new HashMap<String, Object>();
		String orderNumber = Achieve.getUUIDString();
		YsUser wxUserInfo = wxUserMapper.getWxUserInfo(token);
		wxOrderMapper.addOrder(orderNumber, wxUserInfo.getId(), name, type, text, money, addOrderMoney, null, 0,
				new Date(),new Timestamp(System.currentTimeMillis()), 0.0, "0");
		map.put("data", pay(token, String.valueOf(Integer.valueOf(money) * 100), orderNumber));

		return map;
	}

	/**
	 * @return
	 */
	@RequestMapping("/get_money")
	@ResponseBody
	public Map<String, Object> getMoney(String number, HttpServletRequest request) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("data", wxOrderMapper.getEquipmentMoney(number));

		return map;
	}

	/**
	 * 初始化查询定单列表
	 *
	 * @return
	 */
	@RequestMapping("/get_list")
	@ResponseBody
	public Map<String, Object> getList(String token,Integer pageNo,Integer type, HttpServletRequest request,String deviceCode) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();

		YsUser wxUserInfo = wxUserMapper.getWxUserInfo(token);
		Integer start = 1;
		Integer end = 100;
		if(pageNo!=null){
			start = pageNo*10-10;
			end = 10;
		}

		List<Integer> status = new ArrayList<>();
		if(type == null){
			status.add(1);
			status.add(2);
			status.add(3);
			status.add(4);
		}else if(type == 0){
			status.add(1);
			status.add(2);
		}else{
			status.add(3);
			status.add(4);
		}
		// 初始化查询定单列表，已经在sql层面将开关灯相关定单排除
		List<WxOrder> wxOrderLIst = wxOrderMapper.getList(wxUserInfo.getId(),start,end,status,deviceCode);
		// WxUserWallet
		// wxUserWallet=wxUserWalletMapper.getUserWallet(wxUserInfo.getId());
		// 余额开机与其他下单方式采用相同的处理方式，不再单独处理
		/*
		 * for(WxOrder wxOrder:wxOrderLIst){
		 *
		 * if(wxOrder.getType().equals("1")){
		 *
		 * Double equipmentMoney=wxOrderMapper.getEquipmentMoney(wxOrder.getEquipment().
		 * getNumber());
		 *
		 * int i= (int)
		 * (Double.valueOf(wxUserWallet.getMoney())/Double.valueOf(equipmentMoney));
		 * long l=i*60*60*1000L; wxOrder.setDate(l); } }
		 */
		map.put("data", wxOrderLIst);
//		if(type==0){
//			Map<String, List<WxOrder>> equipmentNumberMap = wxOrderLIst.stream().collect(Collectors.groupingBy(WxOrder::getEquipmentNumber));
//			for (String key :equipmentNumberMap.keySet()) {
//				String orders = equipmentNumberMap.get(key).get(0).getEquipment().getOrders();
//				if(orders!=null){
//					List<WxOrder> wxOrderList = wxOrderMapper.getListByid(orders);
//					equipmentNumberMap.put(key,wxOrderList);
//				}
//			}
//			map.put("numberOrder", equipmentNumberMap);
//		}

        return map;
	}

	/**
	 * @return
	 */
	@RequestMapping("/add_order")
	@ResponseBody
	public Map<String, Object> addOrder(String token, HttpServletRequest request) throws ParseException {

	    synchronized (token.intern()){
            Map<String, Object> map = new HashMap<String, Object>();
            YsUser wxUserInfo = wxUserMapper.getWxUserInfo(token);
            Integer lastOrder = wxOrderMapper.getLastOrder(wxUserInfo.getId(), 2*60*60, Integer.parseInt(request.getParameter("type")),request.getParameter("equipment"));
            if(lastOrder >0){
                map.put("data", "请勿重复下单!");
                map.put("code", 1);
                return map;
            }
            return wxOrderService.downOrder(wxUserInfo, request);
        }

	}

	/**
	 * @return
	 */
	@RequestMapping("/get_order")
	@ResponseBody
	public Map<String, Object> getOrder(String number, HttpServletRequest request) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		WxOrder wxOrder = wxOrderMapper.getOrder(number);

		map.put("data", wxOrder);

		return map;
	}

	/**
	 * @return
	 */
	@RequestMapping("/update_order")
	@ResponseBody
	public Map<String, Object> updateOrder(String equipment,String number, HttpServletRequest request){
		return wxOrderService.updateOrder(equipment,number, "");
	}

	/**
	 * 主动关机指令
	 *
	 * @return
	 */
	@RequestMapping("/addCommand")
	@ResponseBody
	public Map<String, Object> addCommand(String number, String equipment, HttpServletRequest request)
			throws ParseException {
		System.out.println("=============================请求get_equiment_status");
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> maps = new HashMap<String, Object>();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("type", "1");
		List<String> list = wxOrderMapper.getListEquipment(number);

		jsonObject.put("orderNumber", list);
		maps.put("code", "0");
		maps.put("msg", "success");
		maps.put("data", jsonObject);
		wxOrderMapper.addCommand(equipment, number, JSONObject.fromObject(maps).toString());

		map.put("data", wxOrderMapper.getTime(number));// 返回定单结束时间，便于前台统计剩余时长

		return map;
	}

	/**
	 * 主动关机指令
	 *
	 * @return
	 */
	@RequestMapping("/closeOrder")
	@ResponseBody
	public Map<String, Object> closeOrder(String number,String equipment)
			throws ParseException {
		if(StringUtils.isNoneBlank(equipment)){
			List<Integer> status = new ArrayList<>();
			status.add(2);
			List<WxOrder> wxOrderList = wxOrderMapper.getList(null,0,1000,status,equipment);
			for (int i = 0; i < wxOrderList.size(); i++) {
				WxOrder wxOrder = wxOrderList.get(i);
				String orderNumber = wxOrder.getOrderNumber();
				wxOrderMapper.setOrder(orderNumber, "", 4, "", "");
				// 为代理商增加分佣和分佣记录
				// 如果orderMoney不为null的话，money和orderMoney是相等的
				wxAgentsRecordingService.saveAgentRecordingForAgents(wxOrder.getEquipment().getNumber(), number, new Double(wxOrder.getOrderMoney()), new Double(wxOrder.getOrderMoney()));
			}
		}else{
			WxOrder wxOrder = wxOrderMapper.getOrder(number);
			String orderNumber = wxOrder.getOrderNumber();
			wxOrderMapper.setOrder(orderNumber, "", 4, "", "");
			// 为代理商增加分佣和分佣记录
			// 如果orderMoney不为null的话，money和orderMoney是相等的
			wxAgentsRecordingService.saveAgentRecordingForAgents(wxOrder.getEquipment().getNumber(), number, new Double(wxOrder.getOrderMoney()), new Double(wxOrder.getOrderMoney()));
		}

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "0");
        map.put("msg", "success");
		return map;
	}

	/**
	 * 获取指定定单信息
	 *
	 * @return
	 */
	@RequestMapping("/get_order_time")
	@ResponseBody
	public Map<String, Object> getOrderTime(String number, String token, HttpServletRequest request)
			throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		// YsUser wxUserInfo = wxUserMapper.getWxUserInfo(token);

		// WxUserWallet
		// wxUserWallet=wxUserWalletMapper.getUserWallet(wxUserInfo.getId());

		WxOrders wxOrder = wxOrderMapper.getOrderMap(number);
		// 不再单独计算余额开机定单剩余时长
		/*
		 * if(wxOrder.getType().equals("1")){
		 *
		 * Double equipmentMoney=wxOrderMapper.getEquipmentMoney(wxOrder.getEquipment().
		 * getNumber());
		 *
		 * int i= (int)
		 * (Double.valueOf(wxUserWallet.getMoney())/Double.valueOf(equipmentMoney));
		 * long l=i*60*60*1000L; wxOrder.setDate(l);
		 *
		 * }
		 */
		// 此处将time字段设为endTime的值显得多余，前台计算时间的算法为：定单创建时间戳+定单总长对应毫秒数-当前时间戳
		// wxOrder.setTime(wxOrder.getEndTime().getTime());
		// System.out.println(wxOrder.toString());
		map.put("data", wxOrder);

		return map;
	}

	/**
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public Map<String, Object> get_openId(String token, String type, HttpServletRequest request) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();

		YsUser wxUserInfo = wxUserMapper.getWxUserInfo(token);
		WxOrder wxOrder = new WxOrder();
		WxUser wxUser = new WxUser();
		wxUser.setId(wxUserInfo.getId());
		wxOrder.setUser(wxUser);
		wxOrder.setStatus("1");
		wxOrder.setType(type);
		map.put("data", wxOrderMapper.findList(wxOrder));
		map.put("code", 0);
		return map;
	}

	/**
	 * 获取设备开机状态
	 *
	 * @return
	 */
	@RequestMapping("/get_equiment_status")
	@ResponseBody
	public Map<String, Object> getEquipmentStatus(String number, HttpServletRequest request) throws ParseException {
		System.out.println("=============================请求get_equiment_status");
		Map<String, Object> map = new HashMap<String, Object>();
		// 根据number查询设备状态
		map.put("data", yjEquipmentMapper.findUniqueByProperty("number", number));
		map.put("code", 0);
		return map;
	}

	/**
	 * @return
	 */
	@RequestMapping("/add_comment")
	@ResponseBody
	public Map<String, Object> addComment(String token, HttpServletRequest request) throws ParseException {
		System.out.println("=============================请求add_comment");
		String text = request.getParameter("text");
		String purification = request.getParameter("purification");
		String noise = request.getParameter("noise");
		String light = request.getParameter("light");
		String number = request.getParameter("number");
		Map<String, Object> map = new HashMap<String, Object>();

		wxOrderMapper.addComment(text, purification, noise, light, number);

		map.put("data", wxOrderMapper.setOrderComment(number));
		map.put("code", 0);
		return map;
	}

	@RequestMapping("/returnOrder")
	@ResponseBody
	public Map<String, Object> returnOrder(String token, HttpServletRequest request) throws ParseException {
		System.out.println("=============================请求returnOrder");
		String equipment = request.getParameter("equipment");
		String number = request.getParameter("number");
		String state = request.getParameter("state");
		//判断设备返回状态
		if(state.equals("jhError") || state.equals("mjError")){
			//退款
			return wxOrderService.returnOrder(number,state);
		}else{
			//修改订单状态
			return wxOrderService.updateOrder(equipment,number, state);
		}

	}

	/***
	 * 支付
	 *
	 * @param token
	 * @param money
	 * @return
	 * @throws ParseException
	 */
	private TreeMap<Object, Object> pay(String token, String money, String orderNumber) throws ParseException {

		String appid = Global.getConfig("appId");// 应用ID
		String mi_ch = Global.getConfig("mch_id");// 应用密钥
		String partnerkey = Global.getConfig("partnerKey");// 应用密钥
		TreeMap<Object, Object> returnMap = new TreeMap<Object, Object>();
		// 排序参数
		String str = getRandomString(32);
		String number = orderNumber;
		SortedMap<Object, Object> params = new TreeMap<Object, Object>();
		params.put("appid", appid);
		params.put("mch_id", mi_ch);
		params.put("nonce_str", str);
		params.put("body", "支付认证");
		params.put("out_trade_no", number);

		params.put("total_fee", money);
		params.put("spbill_create_ip", "192.168.0.11");
		params.put("notify_url", Global.getConfig("notify_url"));
		params.put("trade_type", "JSAPI");
		params.put("openid", token);
		String sign = createSign(params, partnerkey);
		params.put("sign", sign);
		// 拼接XML参数
		String requestXML = getRequestXml(params);
        logger.debug("微信支付请求信息:"+requestXML);
		// 向微信发起支付请求
		String responseXML = myhttpsRequest(unified_url, "POST", requestXML);
		Map<String, String> responseMap = null;
		try {
			responseMap = doXMLParse(responseXML);
			logger.debug("微信支付返回信息:"+responseMap.toString());
			System.out.println(responseMap.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (responseMap.get("return_code").equals("FAIL")) {
			returnMap.put("msg", responseMap.get("return_msg"));

		}
		String prepay_id2 = "prepay_id=" + responseMap.get("prepay_id");

		// 开始装填返回参数
		returnMap.put("appId", appid);
		returnMap.put("timeStamp", Sha1Util.getTimeStamp());
		returnMap.put("nonceStr", str);
		returnMap.put("package", prepay_id2);
		returnMap.put("signType", "MD5");
		returnMap.put("paySign", createSign(returnMap, partnerkey));

		return returnMap;

	}

	/***
	 * 微信
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "wx_callback_alipay")
	@ResponseBody
	public String wxCallbackAlipay(HttpServletRequest request, HttpServletResponse response) throws Exception {

		response.setContentType("text/xml; charset=UTF-8");
		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		ReceiveXmlEntity receiveXmlEntity = getOrderEntity(sb.toString(), ReceiveXmlEntity.class);
		/** 商户订单号 */
		String outTradeNo = receiveXmlEntity.getout_trade_no();
		/** 是否成功 */
		String result_code = receiveXmlEntity.getresult_code();
		/** 微信订单号 */
		String transaction_id = receiveXmlEntity.gettransaction_id();
		if (result_code.equals("SUCCESS")) {
			// 判断是否已支付
			WxOrder order = wxOrderMapper.getOrder(outTradeNo);
			// 是否为第一次付款
			if (order.getStatus().equals("0")) {
				System.out.println(transaction_id);
				wxOrderMapper.setOrder(outTradeNo, transaction_id, 1, "", "");
				wxUserWalletService.setAddMoney(order.getOrderMoney(), order.getAddOrderMoney(), order.getOrderNumber(),"充值");

				wxGoodsRecordService.createGoodsRecord(outTradeNo,order.getUser().getId(),order.getOrderMoney());
			}
		}

		HashMap var211 = new HashMap();
		var211.put("return_code", "SUCCESS");
		var211.put("return_msg", "OK");
		String str = MoneyUtils.createXML(var211);

		return str;
	}

	/**
	 * 将请求参数转换为xml格式的string
	 *
	 * @param parameters
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String getRequestXml(SortedMap<Object, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
				sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
			} else {
				sb.append("<" + k + ">" + v + "</" + k + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}

	// 随机字符串
	public static String getRandomString(int length) { // length表示生成字符串的长度
		String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	public static final String paycharset = "UTF-8";

	public ReceiveXmlEntity getOrderEntity(String strXml, Class c) {
		ReceiveXmlEntity msg = null;

		try {
			if (strXml.length() <= 0 || strXml == null) {
				return null;
			}

			Document var10 = DocumentHelper.parseText(strXml);
			Element root = var10.getRootElement();
			Iterator iter = root.elementIterator();
			msg = (ReceiveXmlEntity) c.newInstance();
			while (iter.hasNext()) {
				try {
					Element ele = (Element) iter.next();
					Field field = c.getDeclaredField(ele.getName());
					Method method = c.getDeclaredMethod("set" + ele.getName(), new Class[] { field.getType() });
					method.invoke(msg, new Object[] { ele.getText() });
				} catch (NoSuchFieldException var) {
				}
			}
		} catch (Exception var101) {
			var101.printStackTrace();
		}

		return msg;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map doXMLParse(String strxml) throws Exception {

		strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

		if (null == strxml || "".equals(strxml)) {

			return null;

		}

		Map m = new HashMap();

		InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));

		SAXBuilder builder = new SAXBuilder();

		org.jdom.Document doc = builder.build(in);

		org.jdom.Element root = doc.getRootElement();

		List list = root.getChildren();

		Iterator it = list.iterator();

		while (it.hasNext()) {

			org.jdom.Element e = (org.jdom.Element) it.next();

			String k = e.getName();

			String v = "";

			List children = e.getChildren();

			if (children.isEmpty()) {

				v = e.getTextNormalize();

			} else {

				v = getChildrenText(children);

			}

			m.put(k, v);

		}

		// 关闭流

		in.close();

		return m;

	}

	/**
	 * 获取子结点的xml
	 *
	 * @param children
	 * @return String
	 */
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				org.jdom.Element e = (org.jdom.Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if (!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}

		return sb.toString();
	}

	/**
	 * 发送https请求
	 *
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式（GET、POST）
	 * @param outputStr
	 *            提交的数据(xml)
	 * @return 返回微信服务器响应的信息
	 */
	public static String myhttpsRequest(String requestUrl, String requestMethod, String outputStr) {
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			java.net.URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(ssf);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			conn.setRequestMethod(requestMethod);
			conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
			// 当outputStr不为null时向输出流写数据
			if (null != outputStr) {
				OutputStream outputStream = conn.getOutputStream();
				// 注意编码格式
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			// 从输入流读取返回内容
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			// 释放资源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			conn.disconnect();
			return buffer.toString();
		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	public static String createSign(SortedMap<Object, Object> parameters, String key) {
		String charSet = paycharset;
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = String.valueOf(entry.getValue());
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + key);
		String sign = MD5Util.MD5Encode(sb.toString(), charSet).toUpperCase();
		return sign;
	}

}
